package com.app.mingluxing.chat;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.app.mingluxing.R;
import com.app.mingluxing.adapter.ChooseNumsAdapter;
import com.app.mingluxing.adapter.ChooseNumsRecyAdapter;
import com.app.mingluxing.adapter.RemoveNumsAdapter;
import com.app.mingluxing.adapter.RemoveNumsRecyAdapter;
import com.app.mingluxing.base.BaseActivity;
import com.app.mingluxing.bean.AddressBean;
import com.app.mingluxing.bean.GroupSettingBean;
import com.app.mingluxing.bean.MessageBean;
import com.app.mingluxing.bean.TopicBean;
import com.app.mingluxing.mqtt.MqttManager;
import com.app.mingluxing.net.HttpUtil;
import com.app.mingluxing.sort.CharacterParser;
import com.app.mingluxing.sort.ChooseNumsComparator;
import com.app.mingluxing.sort.DelNumsComparator;
import com.app.mingluxing.sort.SideBarView;
import com.app.mingluxing.utils.CommonUtils;
import com.app.mingluxing.utils.Constant;
import com.app.mingluxing.utils.DividerItemDecoration;
import com.app.mingluxing.utils.GroupFaceUtils;
import com.app.mingluxing.utils.QiniuUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 创建群聊时 选择群成员页面 / 群设置中添加,删除群成员页面
 * Created by Aaron on 16/1/21.
 */
public class ChooseGroupNumsActivity extends BaseActivity {

    private TextView tvcancel;
    private TextView tvdone;
    private ListView lvcontracts;
    //所有的联系人的集合
    private List<AddressBean.ContactsEntity> contacts = new ArrayList<>();
    //选中的联系人的集合
    private List<AddressBean.ContactsEntity> choosedContacts = new ArrayList<>();
    //等待删除的集合
    private ArrayList<GroupSettingBean.TopicEntity.UserListEntity> waitRemoveList = new ArrayList<>();
    private ChooseNumsAdapter addAdapter;
    private RecyclerView rv_nums;
    private ChooseNumsRecyAdapter recyAdapter;
    private String groupName;//群昵称

    private String originalGroupName;//初始的群昵称, 如果初始群昵称修改过 则不再修改群昵称了
    private ArrayList<GroupSettingBean.TopicEntity.UserListEntity> copyList = new ArrayList<>();//添加群成员时copy的原成员的集合

    private RemoveNumsAdapter removeAdapter;
    private RemoveNumsRecyAdapter removeNumsRecyAdapter;
    private GroupSettingBean.TopicEntity addNums;//添加群成员
    private GroupSettingBean.TopicEntity removeNums;//删除群成员
    private List<String> addedIdList = new ArrayList<>();//已经在群里的成员的集合

    private List<String> imageUrls;//群聊头像的集合
    private JSONObject j;

    private int style;

    /**
     * 创建群 删除群 添加群成员
     */
    private static final int ADD_GROUP_NUMS = 0x32;
    private static final int DEL_GROUP_NUMS = 0x33;
    private static final int CREATE_GROUP = 0x34;

    private SideBarView sidrbar;

    /**
     * 汉字转换拼音的类
     */
    private CharacterParser characterParser;
    //根据拼音来排列ListView里面的数据类
    private ChooseNumsComparator comparator;
    private DelNumsComparator delNumsComparator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_choose_group_nums);

        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        comparator = new ChooseNumsComparator();
        delNumsComparator = new DelNumsComparator();

        initWidget();

        originalGroupName = getIntent().getStringExtra("groupName");

        switch (getIntent().getIntExtra("style", -1)) {

            case Constant.CREATE_GROUP://创建群

                getFriendList();  // 获取好友列表

                break;

            case Constant.ADD_GROUP_NUMS://添加群成员

                addNums = getIntent().getParcelableExtra("addNums");

                getFriendList(); // 获取好友列表

                break;
            case Constant.DELETE_GROUP_NUMS://删除群成员

                removeNums = getIntent().getParcelableExtra("removeNums");
                copyList.addAll(removeNums.userList);
                setDeleteData();

                break;

        }

    }


    private void initWidget() {

        this.lvcontracts = (ListView) findViewById(R.id.lv_contracts);
        this.tvdone = (TextView) findViewById(R.id.tv_done);
        this.tvcancel = (TextView) findViewById(R.id.tv_cancel);

        sidrbar = (SideBarView) findViewById(R.id.sidrbar);

        rv_nums = (RecyclerView) findViewById(R.id.rv_nums);

        rv_nums.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_nums.setLayoutManager(linearLayoutManager);
        rv_nums.setItemAnimator(new DefaultItemAnimator());
        rv_nums.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL_LIST));

        tvdone.setOnClickListener(this);
        tvcancel.setOnClickListener(this);

        //设置右侧触摸监听
        sidrbar.setOnTouchingLetterChangedListener(new SideBarView.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = addAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    lvcontracts.setSelection(position);

                }

            }
        });

    }

    /**
     * 获取通讯录
     */
    private void getFriendList() {

        JSONObject j = new JSONObject();

        j.put("token", sp.getString(Constant.TOKEN, ""));

        HttpUtil.setPostRequest("获取中...", this, Constant.WEB_ROOT_TALK + Constant.MYCONTACTS,
                j.toString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            AddressBean ab = JSONObject.parseObject(str, AddressBean.class);

                            if (ab.code == Constant.STATUS_SUCCESS) {

                                handleResult(ab.contacts);

                            } else {
                                showToast(Constant.showErrorMsg(ab.code, ChooseGroupNumsActivity.this));
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }, null);

    }

    /**
     * 处理数据
     *
     * @param cont
     */
    private void handleResult(List<AddressBean.ContactsEntity> cont) {

//        this.contacts = cont;
//        addAdapter = new ChooseNumsAdapter(this, cont);

        if (addNums != null && addNums.userList != null) {//添加群成员的情况
            //遍历 看好友是否已经在群里
            for (int i = 0; i < cont.size(); i++) {

                String pinyin = characterParser.getSelling(cont.get(i).user.nickName);
                String sortString = pinyin.substring(0, 1).toUpperCase();

                // 正则表达式 判断首字母是否是英文字母
                if (sortString.matches("[A-Z]")) {
                    cont.get(i).user.sortLetters = sortString.toUpperCase();
                } else {
                    cont.get(i).user.sortLetters = "#";
                }

                for (int j = 0; j < addNums.userList.size(); j++) {

                    if (addNums.userList.get(j).user.phoneNum.equals(cont.get(i).user.phoneNum)) {
                        cont.get(i).hasAdded = true;
                        addedIdList.add(cont.get(i).user.phoneNum);
                        break;
                    }

                }
            }
        }else { //删除群成员 和 创建群聊的情况

            for (int i = 0; i < cont.size(); i++) {

                String pinyin = characterParser.getSelling(cont.get(i).user.nickName);
                String sortString = pinyin.substring(0, 1).toUpperCase();

                // 正则表达式 判断首字母是否是英文字母
                if (sortString.matches("[A-Z]")) {
                    cont.get(i).user.sortLetters = sortString.toUpperCase();
                } else {
                    cont.get(i).user.sortLetters = "#";
                }
            }

        }

        // 根据a-z进行排序源数据
        Collections.sort(cont, comparator);

        this.contacts = cont;

        recyAdapter = new ChooseNumsRecyAdapter(this, choosedContacts);
        rv_nums.setAdapter(recyAdapter);

        addAdapter = new ChooseNumsAdapter(this, cont);
        lvcontracts.setAdapter(addAdapter);

        lvcontracts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                try {

                    if (contacts == null || addAdapter == null)
                        return;

                    //如果是群里已经存在的人 则return
                    if (addedIdList != null && contacts.get(position) != null &&
                            contacts.get(position).user != null &&
                            addedIdList.contains(contacts.get(position).user.phoneNum))
                        return;

                    if (contacts.get(position).isSelect)
                        choosedContacts.remove(contacts.get(position));
                    else
                        choosedContacts.add(contacts.get(position));

                    contacts.get(position).isSelect = !contacts.get(position).isSelect;
                    recyAdapter.notifyDataSetChanged();

                    addAdapter.notifyDataSetChanged();

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

    }

    /**
     * 设置删除群成员数据
     */
    private void setDeleteData() {

        if (removeNums == null || removeNums.userList == null)
            return;

        for (int i = 0; i < removeNums.userList.size(); i++) {

//            GroupSettingBean.TopicEntity.UserListEntity userListEntity = removeNums.userList.get(i);

            String pinyin = characterParser.getSelling(removeNums.userList.get(i).user.nickName);
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式 判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                removeNums.userList.get(i).user.sortLetters = sortString.toUpperCase();
            } else {
                removeNums.userList.get(i).user.sortLetters = "#";
            }

        }

        Collections.sort(removeNums.userList, delNumsComparator);

        removeAdapter = new RemoveNumsAdapter(this, removeNums.userList);
        lvcontracts.setAdapter(removeAdapter);

        removeNumsRecyAdapter = new RemoveNumsRecyAdapter(ChooseGroupNumsActivity.this, waitRemoveList);
        rv_nums.setAdapter(removeNumsRecyAdapter);

        lvcontracts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (removeNums.userList == null || removeNums.userList.get(position) == null)
                    return;

                if (removeNums.userList.get(position).user != null
                        && sp.getString(Constant.MOBILE, "").equals(removeNums.userList.get(position).user.phoneNum))
                    return;//不能删除自己

                if (removeNums.userList.get(position).isSelect) {
                    waitRemoveList.remove(removeNums.userList.get(position));
                    if (copyList != null)
                        copyList.add(removeNums.userList.get(position));
                } else {
                    waitRemoveList.add(removeNums.userList.get(position));
                    if (copyList != null)
                        copyList.remove(removeNums.userList.get(position));
                }

                removeNums.userList.get(position).isSelect = !removeNums.userList.get(position).isSelect;
                removeNumsRecyAdapter.notifyDataSetChanged();

                removeAdapter.notifyDataSetChanged();

            }
        });
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {

            case R.id.tv_done://确定

                //判断是 创建群的 还是添加群成员的 还是删除群成员的
                chooseOperation();

                break;

            case R.id.tv_cancel://取消
                finish();
                break;

        }
    }

    /**
     * 判断是 创建群的 还是添加群成员的 还是删除群成员的
     */
    private void chooseOperation() {

        if (removeNums != null && removeNums.userList != null) {//删除群成员

            style = DEL_GROUP_NUMS;

            if (waitRemoveList == null || waitRemoveList.size() < 1) {

                showToast("请选择删除的成员");

                return;
            }

            deleteNums();

        } else if (addNums != null && addNums.userList != null) {//添加群成员

            if (!CommonUtils.isFriendOrGroupNum(sp, this, addNums.topic)) {
                return;
            }

            if (choosedContacts == null || choosedContacts.size() < 1) {
                showToast("请选择添加的好友");
                return;
            }
            style = ADD_GROUP_NUMS;
            addGroupNums();

        } else {//创建群

            style = CREATE_GROUP;
            createGroup();
        }

    }

    /**
     * 删除群成员
     */
    private void deleteNums() {

        if (removeNums == null || removeNums.userList == null || copyList == null)
            return;

        if (copyList.size() < 3) {
            showToast("群聊不能少于三人!");
            return;
        }

        j = new JSONObject();
        List<String> imageUrls = new ArrayList<>();//群聊头像的集合

        StringBuilder sbList = new StringBuilder();

        boolean change = false;//群昵称是否修改过
        for (int i = 0; i < removeNums.userList.size(); i++) {

            if (!originalGroupName.contains(removeNums.userList.get(i).user.nickName)) {//不包含, 说明修改了群名片
                change = true;
                break;
            }

        }

        if (change) {//修改过, 群昵称 还设置为原来的群昵称
            sbList.append(originalGroupName);
        }

        //删除之后的 成员集合

        List<Object> afterList = new ArrayList<Object>();

        if (change)
            getNumsList(afterList, copyList, null, imageUrls);
        else
            getNumsList(afterList, copyList, sbList, imageUrls);

        //删除的 成员集合
        List<Object> removeNumList = new ArrayList<Object>();
        getNumsList(removeNumList, waitRemoveList, null, null);

        if (!change) {
            //删除最后一个, 符号
            sbList.delete(sbList.length() - 1, sbList.length());
            if (afterList.size() > 9) {
                sbList.append("...");
            }
        }

        addData2J(afterList, new ArrayList<Object>(), removeNumList, removeNums.topic, sbList.toString());

        //制作群聊头像
        this.imageUrls = imageUrls;
        new MyAsyncTask().execute();

    }

    /**
     * 给json集合赋值数据
     */
    private void getNumsList(List<Object> userList, ArrayList<GroupSettingBean.TopicEntity.UserListEntity> numList, StringBuilder sb, List<String> imageUrls) {

        if (numList == null)
            return;

        for (int i = 0; i < numList.size(); i++) {

            if (numList.get(i) == null && numList.get(i).user == null)
                continue;

            Map<String, Object> num = new HashMap<String, Object>();

            if (imageUrls != null)
                imageUrls.add(numList.get(i).user.imgUrl);//制作头像的图片集合

            num.put("imgUrl", numList.get(i).user.imgUrl);
            num.put("nickName", numList.get(i).user.nickName);
            num.put("phoneNum", numList.get(i).user.phoneNum);
            num.put("isAdmin", numList.get(i).isAdmin);

            userList.add(num);

            if (sb != null) {
                if (i > 9)//如果人数大于9个 群昵称就不再添加了
                    continue;
                sb.append(numList.get(i).user.nickName + "、");

            }

        }

    }

    /**
     * 添加群成员
     */
    private void addGroupNums() {

        if (choosedContacts == null)
            return;

        j = new JSONObject();

        List<Object> userList = new ArrayList<Object>();

        List<String> imageUrls = new ArrayList<>();//群聊头像的集合

        StringBuilder sbNewName = new StringBuilder();

        boolean change = false;//群昵称是否修改过
        if (!CommonUtils.isNull(originalGroupName)) {

            for (int i = 0; i < addNums.userList.size(); i++) {

                String nickName = addNums.userList.get(i).user.nickName;

                if (!originalGroupName.contains(nickName)) {//不包含, 说明修改了群名片
                    change = true;
                    break;
                }

            }

            if (change) {//修改过, 群昵称 还设置为原来的群昵称
                sbNewName.append(originalGroupName);
            }

        }

        //获取新的成员的集合
        if (change)
            getNewNumsList(userList, null, imageUrls);
        else
            getNewNumsList(userList, sbNewName, imageUrls);

        List<Object> addList = new ArrayList<Object>();

        addList.addAll(userList);

        //获取 群原来成员的集合
        if (addNums != null) {

            if (change)
                getNumsList(userList, addNums.userList, null, imageUrls);
            else
                getNumsList(userList, addNums.userList, sbNewName, imageUrls);
        }

        if (!change) {
            //删除最后一个, 符号
            sbNewName.delete(sbNewName.length() - 1, sbNewName.length());
            if (userList.size() > 9) {
                sbNewName.append("...");
            }
        }

        addData2J(userList, addList, new ArrayList<>(), addNums.topic, sbNewName.toString());

        //制作群聊头像
        this.imageUrls = imageUrls;
        new MyAsyncTask().execute();
    }

    /**
     * 创建群聊
     */
    private void createGroup() {

        if (choosedContacts == null)
            return;

        if (choosedContacts.size() < 2) {
            showToast("至少选择两个人");
            return;
        }

        j = new JSONObject();
        List<Object> userList = new ArrayList<>();
        List<String> imageUrls = new ArrayList<>();//群聊头像的集合

//        imageUrls = new ArrayList<>();
        //添加本人到群里
        addMy2Group(imageUrls, userList);

        StringBuilder groupName = new StringBuilder();
        groupName.append(sp.getString(Constant.NICKNAME, "") + "、");
        //添加成员到群里
        getNewNumsList(userList, groupName, imageUrls);

        //删除最后一个, 符号
        groupName.delete(groupName.length() - 1, groupName.length());
        if (choosedContacts.size() > 9) {
            groupName.append("...");
        }

        addData2J(userList, userList, new ArrayList<Object>(), "", groupName.toString());

        this.imageUrls = imageUrls;

        //制作群聊头像
        new MyAsyncTask().execute();

    }

    /**
     * 往 json中添加数据
     *
     * @param userList   操作之后的群成员集合
     * @param addList    添加的成员集合
     * @param removeList 删除群成员的集合
     * @param topic      添加或者删除的群的 topic
     * @param groupName  群昵称
     */
    private void addData2J(List<Object> userList, List<Object> addList, List<Object> removeList, String topic, String groupName) {

        if (j == null)
            return;

        j.put("userList", userList);//操作之后的群成员集合
        j.put("addList", addList);//添加的成员集合
        j.put("removeList", removeList);//删除群成员的集合
        j.put("topic", topic);//添加或者删除的群的 topic
        j.put("groupName", groupName);
        //如果 原始群昵称不包含 原始群成员的昵称时, 则不修改群昵称
        j.put("token", sp.getString(Constant.TOKEN, ""));

        this.groupName = groupName;
    }

    /**
     * 获取新的群成员的集合
     *
     * @param addList
     */
    private void getNewNumsList(List<Object> addList, StringBuilder sbName, List<String> imageUrls) {

        for (int i = 0; i < choosedContacts.size(); i++) {

            if (choosedContacts.get(i) == null || choosedContacts.get(i).user == null)
                continue;

            Map<String, Object> num = new HashMap<String, Object>();

            imageUrls.add(choosedContacts.get(i).user.imgUrl);//制作头像的图片集合

            num.put("imgUrl", choosedContacts.get(i).user.imgUrl);
            num.put("nickName", choosedContacts.get(i).user.nickName);
            num.put("phoneNum", choosedContacts.get(i).user.phoneNum);
            num.put("isAdmin", 0);

            addList.add(num);

            //群昵称
            if (sbName != null) {
                if (i > 9)//如果人数大于9个 群昵称就不再添加了
                    continue;
                sbName.append(choosedContacts.get(i).user.nickName + "、");
            }

        }

    }

    /**
     * 添加本人到群里
     *
     * @param imageUrls
     * @param userList
     */
    private void addMy2Group(List<String> imageUrls, List<Object> userList) {

        //添加本人
        Map<String, Object> my = new HashMap<String, Object>();

        my.put("imgUrl", sp.getString(Constant.USERIMG, ""));
        my.put("nickName", sp.getString(Constant.NICKNAME, ""));
        my.put("phoneNum", sp.getString(Constant.USERID, ""));
        my.put("isAdmin", 1);

        userList.add(my);
        imageUrls.add(sp.getString(Constant.USERIMG, ""));//添加本人的头像
    }

    private ProgressDialog show;

    private class MyAsyncTask extends AsyncTask<String, String, Bitmap> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            show = ProgressDialog.show(ChooseGroupNumsActivity.this, "请稍候", "正在创建群聊中...");

        }

        @Override
        protected Bitmap doInBackground(String... params) {

//            return NinePic.getInstance().getSinglePic(ChooseGroupNumsActivity.this, imageUrls);
            return GroupFaceUtils.createGroupFace(ChooseGroupNumsActivity.this, imageUrls);
        }

        @Override
        protected void onPostExecute(final Bitmap bitmap) {

            //请求七牛上传图片
            QiniuUtils.getQiniuPic(CommonUtils.compressByte(bitmap), getApplication(), sp.getString(Constant.TOKEN, ""),
                    new QiniuUtils.QiniuSuccessListener() {
                        @Override
                        public void setOnSuccessListener(String str) {

                            //创建群聊
                            createGroupChat(str);
                        }
                    });

        }

    }

    /**
     * 请求创建群接口
     *
     * @param urlPath
     */
    private void createGroupChat(final String urlPath) {

        if (j == null)
            return;

        j.put("groupImgUrl", urlPath);//群头像

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.WEB_ROOT_TALK + Constant.JOINGROUP, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                try {

                    if (show != null && show.isShowing())
                        show.dismiss();

                    final org.json.JSONObject rb = new org.json.JSONObject(response);

                    int code = rb.getInt("code");

                    if (Constant.STATUS_SUCCESS == code) {

                        final MessageBean mb = new MessageBean();
                        mb.messageType = Constant.MQTTMESSAGENOTICE;
                        mb.sendId = sp.getString(Constant.USERID, "");
                        mb.sendName = sp.getString(Constant.NICKNAME, "");
                        mb.sendPic = sp.getString(Constant.USERIMG, "");
                        mb.receiveName = j.getString("groupName");
                        mb.receivePic = urlPath;

                        switch (style) {

                            case CREATE_GROUP://创建群

                                mb.content = sp.getString(Constant.NICKNAME, "") + "创建了群聊";

                                break;

                            case DEL_GROUP_NUMS://删除群成员

                                mb.content = sp.getString(Constant.NICKNAME, "") + "把" + getRemoveNums() + "移出本群";

                                break;

                            case ADD_GROUP_NUMS://添加群成员

                                mb.content = sp.getString(Constant.NICKNAME, "") + "邀请了" + getAddNums() + "加入群聊";

                                break;

                        }

                        mb.sendDate = System.currentTimeMillis();
                        mb.channelId = rb.getString("topic");
//                        mb.chatType = Constant.CHAT_GROUP;//群聊
//                        MqttManager.getInstance().setMessage(rb.getString("topic"), mb);
                        style = 0; //置为初始值

                        //延迟一秒后发 系统通知
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    MqttManager.getInstance().setMessage(rb.getString("topic"), mb);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }, 1000);

                        //插入群聊的信息
                        updateInfo(mb.channelId, urlPath, mb.receiveName);

//                        进入群聊的页面
                        Intent mIntent = new Intent(ChooseGroupNumsActivity.this, ChatActivity.class);
                        mb.channelId = rb.getString("topic");//群聊的topic
                        mIntent.putExtra("contact", mb);

                        startActivity(mIntent);
                        finish();

                    } else {
                        showToast(Constant.showErrorMsg(code, ChooseGroupNumsActivity.this));
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

                if (show != null && show.isShowing())
                    show.dismiss();

                showToast("失败!");
            }

        }) {

            protected Map<String, String> getParams() {
                Map<String, String> param = new HashMap<String, String>();
                param.put("data", JSON.toJSONString(j, SerializerFeature.DisableCircularReferenceDetect));
                return param;
            }
        };

        //把请求加入队列
        mApplication.addToRequestQueue(stringRequest, getClass().getName());

    }

    private void updateInfo(String topic, String imgUrl, String name) {

        if (Constant.topicMap == null)
            Constant.topicMap = (Map<String, TopicBean>) JSON.parse(sp.getString(Constant.TOPIC_MAP, ""));

        TopicBean tb = new TopicBean();
        tb.topic = topic;
        tb.topicImg = imgUrl;
        tb.topicName = name;
        Constant.topicMap.put(topic, tb);

        sp.edit().putString(Constant.TOPIC_MAP, JSON.toJSONString(Constant.topicMap, true)).apply();

    }

    /**
     * 获取添加的群成员的名称
     *
     * @return
     */
    private String getAddNums() {

        String addNums = "";
        if (choosedContacts != null && choosedContacts.size() > 0) {

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < choosedContacts.size(); i++) {
//                                        String nickName = choosedContacts.get(i).user.nickName;
                sb.append(choosedContacts.get(i).user.nickName + "、");
            }

            addNums = sb.substring(0, sb.length() - 1);

        }
        return addNums;
    }

    /**
     * 获取 删除的群成员的名称
     *
     * @return
     */
    private String getRemoveNums() {

        if (waitRemoveList != null && waitRemoveList.size() > 0) {

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < waitRemoveList.size(); i++) {
//                                        String nickName = choosedContacts.get(i).user.nickName;
                sb.append(waitRemoveList.get(i).user.nickName + "、");
            }

            return sb.substring(0, sb.length() - 1);

        }
        return "";
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mApplication.cancelPendingRequests(getClass().getName());
    }
}
